﻿#include "SLT_tool_pub.h"
#include "SL_asynFramePub.h"
#include "SL_tcpServer.h"
#include "SLT_tcpSender.h"

//请求 5
struct _proxy_cmd_setEnInfoReq_st
{
	std::string  encryption;
	std::string  sessionid;
	AIGC_JSON_HELPER(encryption, sessionid)
};
//通用应答json格式 5->6
class _proxy_cmd_comm_resp_st
{
public:
	int   ret;
	std::string  sessionid;
	std::string  ret_msg;
	AIGC_JSON_HELPER(ret, sessionid, ret_msg)
};
class senderSession : public SLF_SessionBase
{
public:
	virtual void OnStart() {
		SLT_LOG_ERR("服务session start");
	}
	virtual void OnStop() {}
	virtual void OnMsgArrive(SLF_senderPtr& _sender, uint32_t srcSid, int msgid, SLF_sendMemBasePtr& _data)
	{
		
		_proxy_cmd_setEnInfoReq_st req;
		aigc::JsonHelper::JsonToObject2(req, _data->getData());
		SLT_LOG_ERR("recv,srcid:%d,msgid:%d,sessionid:%s", srcSid, msgid, req.sessionid.c_str());

		_proxy_cmd_comm_resp_st resp;
		resp.ret = 1;
		resp.ret_msg = "ok";
		resp.sessionid = req.sessionid;
		std::string retstr;
		aigc::JsonHelper::JsonToObject(resp, retstr);


		SLF_sendMemBasePtr sendmem(new SLF_sendMemBase());
		sendmem->add(retstr.c_str(), retstr.length());
		_sender->SLF_postMsg(srcSid,msgid,getSessID(), sendmem);
	}
	virtual void OnTimer(uint32_t timerID, int _intervalMs, bool periodic)
	{
		if (!m_senderSptr) {
			return;
		}
		setTimer(1, 5000, false);
		send();
	}
	void send() {
		_proxy_cmd_setEnInfoReq_st req;
		req.encryption = "test1";
		req.sessionid = "sessi1";
		std::string strJson;
		aigc::JsonHelper::ObjectToJson(req, strJson);
		SLF_sendMemBasePtr mem(new SLF_sendMemBase());
		mem->m_mem.add(strJson.c_str(), strJson.length() + 1);
		m_senderSptr->SLF_postMsg(0,9999, getSessID(), mem);
	}

	SLTcpServerStpr tcpserverSptr;
	SLT_TCPSenderPtr m_senderSptr;
};



class tcpServerImpl :public SLTcpServerCB
{
public:
	virtual void TcpServer_onConnect(SLTcpClientPtr& _client) {
		SLT_LOG_ERR("接收到连接");
		SLT_getTcpServerSender(_client);
	}
	virtual void TcpServer_onError() {
	}

	void tcp_sender_callback(uint32_t _dstID, int msgid, uint32_t _srcID,
		SLF_sendMemBasePtr& _data, const SLF_senderPtr& _senderPtr, SLF_SessionBasePtr& _in_out_sessSptr)
	{
		//接收消息处理
		if (0 == msgid) {
			//创建接收对象
			SLF_SessionBasePtr sessptr(new senderSession());
			SLF_addSession(sessptr);
			_in_out_sessSptr = sessptr; //返回处理消息的session
		}
	}
};


static tcpServerImpl  g_tcpServerImpl;

#include <functional>
int main()
{
    //使用通用sender进行tcp消息发送。server端
	SLT_logInit();
	SLF_init(1);
	
	SLT_setTcpRecvMsgCb(std::bind(&tcpServerImpl::tcp_sender_callback,&g_tcpServerImpl, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
													std::placeholders::_4, std::placeholders::_5, std::placeholders::_6));
	SLTcpServerStpr tcpserverSptr = sl_createTcpServer();
	tcpserverSptr->init(&g_tcpServerImpl);
	tcpserverSptr->start();

	tcpserverSptr->addListen("127.0.0.1", 32204);

	printf("run success\n");
	getchar();
    return 0;
}